package it.softphone.cmc.server.service.json;


import it.softphone.commons.json.server.JSONConverter;
import it.softphone.commons.json.server.JSONObject;
import it.softphone.commons.service.LogAware;


import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class JSONKeyConverter implements JSONConverter<Key>, LogAware {

	@Override
	public Object convert(Key value) {

		return (value == null ) ? JSONObject.NULL : KeyFactory.keyToString(value);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object convert(Class type, Object value) {
		if( JSONObject.NULL==value || null==value ) return null;
		
		if( value instanceof String ) {
			try {
			return KeyFactory.stringToKey((String) value);
			}
			catch( Exception e ) {
				logger.warn(String.format("key conversion error from value [%s] : [%s]", value, e.getMessage()));
				return null;
			}
		}
		return value;
	}
}


